<template>
	<view class="content">
		<!-- 使用z-paging实现分页加载优惠券列表 -->
		<z-paging ref="pagingRef" v-if="firstLoaded || isCurrentPage" v-model="couponList" @query="queryCouponList"
			:fixed="false">
			<!-- 优惠券列表项 -->
			<view v-for="(item, index) in couponList" :key="index" class="coupon" :style="bgStyle">
				<view class="left-top" v-if="item.usedCategoryName!==null">
					{{item?.usedCategoryName}}
				</view>

				<view class="coupon-left">
					<view class="price">
						<view class="" v-if="item.usedAmount!==null&&item.type===1||item.type===3">
							<text class='icon'>¥</text>
							<text class="price-text">{{ item?.usedAmount }}</text>
						</view>
						<text v-if="item.type===2" class="price-text">{{item?.discount}}折</text>
						<text v-if="item.type===2||item.type===3" class='text2'>无门槛</text>
					</view>
					<view class="coupon-left-box">
						<text class="desc" v-if="item.title!==null">{{item?.title}}</text>
						<text class="data-time"
							v-if="item.validStartTime!==null&&item.validType===1">有效期至{{ item?.validStartTime.slice(0,10)}}</text>
						<text class="data-time"
							v-if="item.validDays!==null&&item.validType===2">自领取之日{{item?.validDays}}日内有效</text>
					</view>
				</view>

				<view class="line"></view>

				<view class="coupon-right">
					<text class="get-btn" @click.stop="handleReceiveCoupon(item)">
						立即领取
					</text>
				</view>
			</view>

			<!-- 空状态提示 -->
			<template #empty>
				<view class="empty-view">暂无优惠券</view>
			</template>
		</z-paging>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		watch,
		nextTick,
		reactive,
		onMounted
	} from "vue";
	import {
		getEffectiveCouponList,
		receiveCoupon
	} from '@/api/coupon.js';
	import {
		getCityCode
	} from "@/common/util.js";
	import {
		ImgBaseUrl
	} from "@/utils/domain.js";
	import {
		onLoad,
	} from '@dcloudio/uni-app';


	// const emit = defineEmits(["reload"]);

	const couponList = ref([]);
	const firstLoaded = ref(false);
	const isCurrentPage = ref(true);
	const pagingRef = ref(null);
	const usedCategory = ref('');
	const state = reactive({
		currentAreaId: ""
	});

	const bgStyle = computed(() => ({
		backgroundImage: `url(${ImgBaseUrl}couponUnclaimed-bg.png)`,
	}));
	onLoad((options) => {
		usedCategory.value = options.itemId
	})
	onMounted(() => {
		nextTick(() => {
			if (pagingRef.value) {
				// pagingRef.value.reload();
			}
		});
	});


	const queryCouponList = async (pageNum, pageSize) => {
		try {
			const params = {
				pageNum: pageNum,
				pageSize,
				type: '',
				usedCity: state.currentAreaId || getCityCode(),
				usedCategory: usedCategory.value,
			};

			const res = await getEffectiveCouponList(params);
			console.log('接口返回数据:', res);

			const listData = Array.isArray(res) ? res : (res.rows || []);
			const total = res.total || listData.length; // 确保 total 有值

			// 标记加载完成
			pagingRef.value.complete(listData, total);
			firstLoaded.value = true;
		} catch (error) {
			console.error('获取优惠券列表失败:', error);
			pagingRef.value.complete(false); // 标记加载失败
		}
	};
	const handleReceiveCoupon = async (item) => {
		if (item.isReceived) return;

		try {
			const res = await receiveCoupon(item.id);
			item.isReceived = true;

			uni.showToast({
				title: res.msg || '领取成功',
				icon: 'success'
			});

			// 重新加载第一页数据
			pagingRef.value.reload();
		} catch (error) {
			console.error('领取优惠券失败:', error);
			uni.showToast({
				title: '领取失败',
				icon: 'none'
			});
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		height: calc(100vh - 80rpx);
		// height: 100vh;
		background-color: #fff;
		padding: 20rpx;
	}

	.coupon {
		width: 100%;
		height: 198rpx;
		background-size: 100% auto;
		background-repeat: no-repeat;
		background-position: top center;
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		margin-bottom: 20rpx;

		.left-top {
			font-weight: 400;
			font-size: 24rpx;
			color: #FF6A47;
			border-radius: 20rpx 0rpx 20rpx 0rpx;
			background: #FFEAE5;
			padding: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			position: absolute;
			top: 0rpx;
			left: 0rpx;
		}

		.coupon-left {
			width: 65%;
			display: flex;
			align-items: center;
			justify-content: space-around;

			.price {
				display: flex;
				flex-direction: column;
				align-items: center;

				.price-text {
					font-size: 70rpx;
					color: #FF6A47;
					font-weight: bold;
				}

				.text2 {
					font-size: 28rpx;
					font-weight: 400;
					color: #FF6A47;
				}

				.icon {
					font-size: 30rpx;
					color: #FF6A47;
					font-weight: bold;
				}
			}

			.coupon-left-box {
				display: flex;
				flex-direction: column;
				height: 90rpx;
				justify-content: space-between;
				align-items: center;

				.desc {
					font-weight: 500;
					color: #FF6A47;
					font-size: 36rpx;
				}

				.data-time {
					font-size: 28rpx;
					font-weight: 400;
					color: #FF6A47;
				}
			}
		}

		.line {
			border: 3rpx dashed #FF6A47;
			height: 108rpx;
			margin-left: 63rpx;
		}

		.coupon-right {
			margin-right: 20rpx;

			.get-btn {
				color: #FF6A47;
				font-size: 30rpx;
				font-weight: 500;
				padding: 8rpx 20rpx;
			}
		}
	}

	.empty-view {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>